package cn.fancy.sdk.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class Md5 {
	public static String md5Digest(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte b = md[i];
				str[k++] = hexDigits[b >> 4 & 0xf];
				str[k++] = hexDigits[b & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String buildSignNotAnd(LinkedHashMap<String, String> str, String key) {
		if (null == str)
			return null;
		StringBuilder sb = new StringBuilder();
		Object[] key_arr = str.keySet().toArray();
		for (int i = 0; i < key_arr.length; i++) {
			sb.append(key_arr[i].toString());
			sb.append("=");
			sb.append(str.get(key_arr[i].toString()));
		}
		sb.append(key);

		String ss = sb.toString();
		Logger.e("build sign", ss);
		return Md5.md5Digest(ss);
	}
	
	public static String gBuildSign(Map<String, String> str, String key,String service,String timee) {
		if (null == str)
			return null;
		StringBuilder sb = new StringBuilder();
		sb.append(service);
		sb.append(timee);
		
		Object[] key_arr = str.keySet().toArray();
		Arrays.sort(key_arr);
		for (int i = 0; i < key_arr.length - 1; i++) {
			sb.append(key_arr[i].toString());
			sb.append("=");
			sb.append(str.get(key_arr[i].toString()));
		}
		sb.append(key_arr[key_arr.length - 1].toString());
		sb.append("=");
		sb.append(str.get(key_arr[key_arr.length - 1].toString()));
		sb.append(key);

		String ss = sb.toString();
		Logger.e("gbuild sign", "gbuild sign:"+ss);
		return Md5.md5Digest(ss);
	}
	
}
